//
//  ResumeViewController.m
//  Topit
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "ResumeViewController.h"
#import "YXYAttentionViewController.h"
#import "YXYLoginViewController.h"
#import "YXYUserProfileViewController.h"
#import "YXYResumeTableViewCell.h"
#import "YXYResumeOnOffTableViewCell.h"
#import "YXYAboutUSViewController.h"
@interface ResumeViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, copy) NSString *cache;
@property (nonatomic, copy) NSString *userProfile;
@end

@implementation ResumeViewController
- (void)dealloc {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [_userProfile release];
    [_tableView release];
    [_cache release];
    [_nightMode release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpTableView];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    [self setUserProfile];
}

- (void)setUserProfile {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *cachePath = [path stringByAppendingPathComponent: @"Caches"];
    self.cache = [NSString stringWithFormat:@"%2.0fM", [self folderSizeAtPath:cachePath]];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *users = [user objectForKey:@"user"];
    if ([users count] == 0) {
        self.userProfile = @"登陆";
    }else {
        self.userProfile = @"个人信息";
    }
    NSUserDefaults *night = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [night objectForKey:@"NightMode"];
    if ([passWord isEqualToString:@"Night"]) {
        self.tableView.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
    }else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.tableView reloadData];
    
}

- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.tableView registerClass:[YXYResumeTableViewCell class] forCellReuseIdentifier:@"YXYResumeTableViewCellIdentifier"];
    [self.tableView registerClass:[YXYResumeOnOffTableViewCell class] forCellReuseIdentifier:@"YXYResumeOnOffTableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    YXYResumeTableViewCell *newCell = [tableView dequeueReusableCellWithIdentifier:@"YXYResumeTableViewCellIdentifier"];
    YXYResumeOnOffTableViewCell *onOffCell = [tableView dequeueReusableCellWithIdentifier:@"YXYResumeOnOffTableViewCellIdentifier"];
    if ([passWord isEqualToString:@"Night"]) {
        cell.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
        newCell.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
        onOffCell.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
    }else {
        cell.backgroundColor = [UIColor whiteColor];
        newCell.backgroundColor = [UIColor whiteColor];
        onOffCell.backgroundColor = [UIColor whiteColor];
    }
//    if (indexPath.row == 0) {
//        cell.textLabel.text = self.userProfile;
//        [cell.textLabel nightMode];
//        return cell;
//    }else
        if (indexPath.row == 0) {
        newCell.label.text = @"缓存";
        [newCell.label nightMode];
        newCell.myLabel.text = self.cache;
        [newCell.myLabel nightMode];
        return newCell;
    }else if (indexPath.row == 1) {
        cell.textLabel.text = @"收藏";
        [cell.textLabel nightMode];
        return cell;
    }else if (indexPath.row == 2) {
        onOffCell.label.text = @"夜间模式";
        [onOffCell.label nightMode];
        if ([passWord isEqualToString:@"Night"]) {
            onOffCell.nightNoOff.on = YES;
        }
        [onOffCell.nightNoOff addTarget:self action:@selector(swithOnOff:) forControlEvents:UIControlEventValueChanged];
        return onOffCell;
    }else {
        cell.textLabel.text = @"关于Topit";
        [cell.textLabel nightMode];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    if (indexPath.row == 0 && [self.userProfile isEqualToString:@"个人信息"]) {
//        YXYUserProfileViewController *userProfoleVC = [[YXYUserProfileViewController alloc] init];
//        [self.navigationController pushViewController:userProfoleVC animated:YES];
//        [userProfoleVC release];
//    }
//    if (indexPath.row == 0 && [self.userProfile isEqualToString:@"登陆"]) {
//        YXYLoginViewController *loginVC = [[YXYLoginViewController alloc] init];
//        loginVC.view.backgroundColor = [UIColor whiteColor];
//        [self.navigationController pushViewController:loginVC animated:YES];
//        [loginVC release];
//    }
    if (indexPath.row == 0) {
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要清除缓存嘛？" preferredStyle:UIAlertControllerStyleAlert];
        [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self cleanAction];
            [self.tableView reloadData];
        }]];
        [alertView addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alertView animated:YES completion:nil];
    }else if (indexPath.row == 1) {
        YXYAttentionViewController *attentionVC = [[YXYAttentionViewController alloc] init];
        [self.navigationController pushViewController:attentionVC animated:YES];
    }else if (indexPath.row == 3) {
        YXYAboutUSViewController *aboutUsVC = [[YXYAboutUSViewController alloc] init];
        aboutUsVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:aboutUsVC animated:YES];
    }
}

- (void)swithOnOff:(UISwitch *)switchPress {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    if ([passWord isEqualToString:@"Night"]) {
        [user setObject:@"Day" forKey:@"NightMode"];
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.tableView.backgroundColor = [UIColor whiteColor];
    }else {
        [user setObject:@"Night" forKey:@"NightMode"];
        self.navigationController.navigationBar.barTintColor = [UIColor grayColor];
        self.tableView.backgroundColor = [UIColor colorWithRed:34 / 255.0 green:34 / 255.0 blue:34 / 255.0 alpha:1];
    }
    
    [center postNotificationName:@"tabbar" object:nil userInfo:nil];
    [self.tableView reloadData];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *users = [user objectForKey:@"user"];
    
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height / 2)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:myView.bounds];
    imageView.image = [UIImage imageNamed:@"Background"];
    [myView addSubview:imageView];
    [imageView release];
    
    UIImageView *idImage = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.width / 2 - 40, 40, 80, 80)];
    idImage.layer.cornerRadius = 40;
    idImage.clipsToBounds = YES;
    
    UILabel *idName = [[UILabel alloc] initWithFrame:CGRectMake(0, idImage.bottom + 10, self.view.width, 20)];
    idName.textAlignment = 1;
    
    if ([users count] == 0) {
        idImage.image = [UIImage imageNamed:@"avatar"];
        idName.text = @"Topit";
    }else {
        [idImage sd_setImageWithURL:[NSURL URLWithString:[users valueForKey:@"image"]]];
        idName.text = [users valueForKey:@"name"];
    }
    [myView addSubview:idImage];
    [idImage release];
    [myView addSubview:idName];
    [idName release];
    
    return myView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.view.height / 2;
}


#warning 清空
-(void)cleanAction
{
    //获取完整路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameAarray = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameAarray) {
            //拼接绝对路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            //通过文件管理者删除文件
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
    self.cache = [NSString stringWithFormat:@"%.2fM",[self folderSizeAtPath:path]];
}

#warning 计算单个文件大小的方法
-(long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil]fileSize];
    }
    return 0;
}

#warning  计算一个文件夹的大小
-(float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    //根据路径获取文件夹里面元素集合
    //获取集合类型的枚举类型
    NSEnumerator *enumeratot = [[manager subpathsAtPath:path] objectEnumerator];
    //每次遍历得到的文件名
    //文件夹的大小
    NSString *fileName = [NSString string];
    float folderSize = 0;
    while ((fileName = [enumeratot nextObject])!= nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    return folderSize/(1024*1024.0);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
